package com.example.f_app;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button btn_play,btn_pause,btn_stop,btn_quit;
    MyConn conn=new MyConn();
    MusicService musicService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        Intent intent =new Intent(this,MusicService.class);
        bindService(intent, conn, BIND_AUTO_CREATE);
    }
    public void initView() {
        btn_play=findViewById(R.id.btn_play);
        btn_pause=findViewById(R.id.btn_pause);
        btn_stop=findViewById(R.id.btn_stop);
        btn_quit=findViewById(R.id.btn_quit);
        btn_play.setOnClickListener(this);
        btn_pause.setOnClickListener(this);
        btn_stop.setOnClickListener(this);
        btn_quit.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_play:
                musicService.play();
                btn_play.setEnabled(false);
                btn_pause.setEnabled(true);
                btn_stop.setEnabled(true);
                break;
            case R.id.btn_pause:
                musicService.pause();
                btn_play.setEnabled(true);
                btn_pause.setEnabled(false);
                btn_stop.setEnabled(true);
                break;
            case R.id.btn_stop:
                musicService.stop();
                btn_play.setEnabled(true);
                btn_pause.setEnabled(false);
                btn_stop.setEnabled(false);
                break;
            case R.id.btn_quit:
                finish();
                break;
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
    }
    class MyConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //获取 MusicBinder 的实例
            MusicService.MusicBinder binder=(MusicService.MusicBinder) service;
            musicService=binder.getService();//返回一个 MusicService 对象
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}
